import json
import os
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from utils.transferUtil import TransferUtil

Base = declarative_base()

class Friend(Base):
    __tablename__ = 'tbl_friend'
    id = Column(Integer, primary_key=True, autoincrement=True)
    userId = Column(Integer)
    username = Column(String(255))
    phone = Column(Integer)
    email = Column(String(255))
    avatar = Column(String(255))
    avatar_local = Column(String(255))
    remark = Column(String(255))

class FriendApply(Base):
    __tablename__ = 'tbl_friend_apply'
    id = Column(Integer, primary_key=True, autoincrement=True)
    senderId = Column(Integer)
    senderName = Column(String)
    receiverId = Column(Integer)
    msgBody = Column(String(255))
    time = Column(Integer)
    status = Column(Integer)
    extra = Column(String(255))

class PullTime(Base):
    __tablename__ = 'tbl_pull_time'
    id = Column(String,primary_key=True)
    time = Column(Integer)

class ChatMsg(Base):
    __tablename__ = 'tbl_msg'
    id = Column(Integer,primary_key=True,autoincrement=True)
    msgId = Column(String(40))
    msgType = Column(Integer)
    msgBody = Column(String(2000))
    sessionId = Column(String(40))
    sessionType = Column(Integer)
    senderId = Column(Integer)
    senderName = Column(String(40))
    seqId = Column(Integer)
    time = Column(Integer)
    status = Column(Integer)
    extra = Column(String(40))




class CommonDao():

    def __init__(self,userId):
        idStr = str(userId)
        documentsPath = '/Users/momo/Documents/walala/' + idStr
        exists = os.path.exists(documentsPath)
        if exists is not True:
            os.makedirs(documentsPath)
        engine = create_engine('sqlite:///' + documentsPath + '/base.db', echo=True,connect_args={'check_same_thread':False},
                    poolclass=StaticPool)
        Base.metadata.create_all(engine)
        Session = sessionmaker(bind=engine)
        self.session = Session()

    #--------------------------msg--------------------------------------------#

    def saveMsg(self,chatMsg):
        self.session.add(chatMsg)
        self.session.commit()

    def updateMsg(self,chatMsg):
        try:
            exist = self.session.query(ChatMsg).filter_by(sessionId=chatMsg.sessionId,msgId=chatMsg.msgId).first()
            msg_ = TransferUtil.obj2DictWithout_(chatMsg)
            msg_.pop('metadata')
            print('ackMsg',json.dumps(msg_))
            print('已存在的消息',exist)
            exist.seqId = chatMsg.seqId
            exist.status = 0
            self.session.commit()
        except Exception as e:
            print(e)

    # -------------------------friend----------------------------------------#

    def getFriendByUserId(self,userId):
        result = self.session.query(Friend).filter_by(userId=userId).first()
        return result

    def addFriend(self,friend):
        self.session.add(friend)
        self.session.commit()

    def updateFriend(self,friend):
        exist = self.session.query(Friend).filter_by(userId=friend.userId).first()
        exist.username = friend.username
        exist.email = friend.email
        exist.phone = friend.phone
        exist.remark = friend.remark
        exist.avatar = friend.avatar
        self.session.commit()

    def getFriendList(self):
        return self.session.query(Friend).all()


    #--------------------------friendApply-----------------------------------

    #查询好友申请
    def getFriendApply(self,senderId,receiverId):
        return self.session.query(FriendApply).filter_by(senderId=senderId,receiverId=receiverId).first()

    #添加好友申请
    def addFriendApply(self,friendApply):
        self.session.add(friendApply)
        self.session.commit()

    #更新好友申请
    def updateFriendApply(self,friendApply):
        pass

    #--------------------------time------------------------------------------

    #获取某个类型的时间
    def getPullTime(self, type):
        return self.session.query(PullTime).filter_by(id=type).first()

    def addTime(self,newTime):
        self.session.add(newTime)
        self.session.commit()

def class_to_dict(obj):
    '''把对象(支持单个对象、list、set)转换成字典'''
    is_list = obj.__class__ == [].__class__
    is_set = obj.__class__ == set().__class__

    if is_list or is_set:
        obj_arr = []
        for o in obj:
            # 把Object对象转换成Dict对象
            dict = {}
            dict.update(o.__dict__)
            obj_arr.append(dict)
        return obj_arr
    else:
        dict = {}
        dict.update(obj.__dict__)
        return dict


if __name__ == '__main__':
    friendApply = FriendApply()
    friendApply.senderId = 1
    friendApply.receiverId = 3
    friendApply.senderName = 'walala'
    friendApply.msgBody = 'aaa'
    friendApply.time = 11111111111
    friendApply.status = 1
    friendApply.extra = '11111'
    dict= class_to_dict(friendApply)
    d2 = TransferUtil.obj2DictWithout_(friendApply)
    print(friendApply)
    print(dict)
    print(d2)
    d2.pop('metadata')
    print(json.dumps(d2))
